package com.ocom.ugcapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.zxing.WriterException;
import com.ocom.common.constant.WxServiceUrl;
import com.ocom.common.entity.card.EntityCardInfo;
import com.ocom.common.entity.card.EntityXfAccountInfo;
import com.ocom.common.entity.company.EntityCompanyConfig;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.master.EntityWechatAppInfo;
import com.ocom.common.entity.master.EntityWechatPerInfo;
import com.ocom.common.entity.pay.EntityAppConfig;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.ugcapi.GetPersonDetailRequest;
import com.ocom.common.request.ugcapi.GzhAppNameVo;
import com.ocom.common.request.ugcapi.GzhChangePersonVo;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.ModifyPersonInfoRequest;
import com.ocom.common.vo.PersonVo;
import com.ocom.common.vo.company.GzhCodeOfComVo;
import com.ocom.common.vo.company.GzhPerInfoVo;
import com.ocom.common.vo.human.UserInfoVo;
import com.ocom.common.vo.human.XfUserInfoVo;
import com.ocom.common.vo.pay.KeySecret;
import com.ocom.common.vo.payconfig.ModifyCardStateRequest;
import com.ocom.common.vo.payconfig.UpdatecardStateVo;
import com.ocom.common.vo.ugcapi.GzhUserInfo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.ugcapi.client.CompanyClientService;
import com.ocom.ugcapi.client.HumanClientService;
import com.ocom.ugcapi.client.PayConfigClientService;
import com.ocom.ugcapi.client.SrvpaccessClientService;
import com.ocom.ugcapi.config.RsaConfig;
import com.ocom.ugcapi.util.RSAHelper;
import com.ocom.ugcapi.vo.UserInfoYkmVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/11/24
 **/
@Slf4j
@RestController
public class PersonController {

	@Autowired
	CompanyClientService companyClientService;

	@Autowired
	HumanClientService humanClientService;

	@Autowired
	SrvpaccessClientService srvpaccessClientService;

	@Autowired
	private PayConfigClientService payConfigClientService;

	@Resource
	private RedisUtil redisUtil;

	@PostMapping(WxServiceUrl.URL_getPersonList)
	public Result getPersonList(@RequestBody Map<String, Object> map) {
		GzhAppNameVo appNameVo = JSON.parseObject(JSON.toJSONString(map), GzhAppNameVo.class);
		return companyClientService.getPersonListByOpenid(appNameVo.getUserInfo().getOpenId(),
				appNameVo.getUserInfo().getAppId());
	}

	@PostMapping(WxServiceUrl.URL_addPersonUrl)
	public Result addPersonUrl(@RequestBody Map<String, Object> map) {
		GzhAppNameVo appNameVo = JSON.parseObject(JSON.toJSONString(map), GzhAppNameVo.class);

		Result result = companyClientService.getAppInfoByName(appNameVo.getAppName());
		if (result.getCode() != 200) {
			return result;
		}
		EntityWechatAppInfo entityWechatAppInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityWechatAppInfo.class);

		Map<String, Object> objectMap = new HashMap<>();

		Result result1 = companyClientService.getGzhCodeOfCom(entityWechatAppInfo.getComId());
		GzhCodeOfComVo gzhCodeOfComVo = JSON.parseObject(JSON.toJSONString(result1.getData()), GzhCodeOfComVo.class);
		objectMap.put("comIdCode", gzhCodeOfComVo.getComIdCode());
		objectMap.put("url", "");

		//读取配置
		Result result2 = companyClientService.getAppFunc(appNameVo.getUserInfo().getComId(), appNameVo.getUserInfo().getAppId());

		if (result2.getCode() != 200) {
			return ResultUtil.success(objectMap);
		}

		EntityAppConfig entityAppConfig = JSON.parseObject(JSON.toJSONString(result2.getData()), EntityAppConfig.class);

		/**
		 * 4、调用单位微服务接口3.16 urlBindRegister（参数：bind、register）获取pageUrl
		 * 如果pageUrl为空，bindUrl :=空
		 * 否则bindUrl := pageUrl + “?AppName=” + app_name + “&com_id_code=” + comIdCode
		 */
		if (entityAppConfig.getBind() > 0) {
			Result result3 = companyClientService.urlBindRegister(entityAppConfig.getBind(), 0);
			if (result3.getCode() == 200) {
				Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(result3.getData()), Map.class);
				//bindUrl := pageUrl + “?AppName=” + app_name + “&com_id_code=” + comIdCode
				objectMap.put("url", map2.get("pageUrl") +
						"?AppName=" + appNameVo.getAppName() +
						"&comIdCode=" + gzhCodeOfComVo.getComIdCode());
			}
		} else {
			Result result3 = companyClientService.urlBindRegister(0, entityAppConfig.getRegister());
			if (result3.getCode() == 200) {
				Map<String, String> map3 = JSON.parseObject(JSON.toJSONString(result3.getData()), Map.class);
				//bindUrl := pageUrl + “?AppName=” + app_name + “&com_id_code=” + comIdCode
				objectMap.put("url", map3.get("pageUrl") +
						"?AppName=" + appNameVo.getAppName() +
						"&comIdCode=" + gzhCodeOfComVo.getComIdCode());
			}
		}
		return ResultUtil.success(objectMap);
	}


	@PostMapping(WxServiceUrl.URL_changePerson)
	public Result changePerson(@RequestBody Map<String, Object> map) {
		GzhChangePersonVo changePersonVo = JSON.parseObject(JSON.toJSONString(map), GzhChangePersonVo.class);

		Result result3 = companyClientService.getPersonListByOpenid(changePersonVo.getUserInfo().getOpenId(),
				changePersonVo.getUserInfo().getAppId());
		if (result3.getCode() != 200) {
			return ResultUtil.error(ResultEnum.Err_2036);
		}
		List<GzhPerInfoVo> list = JSON.parseArray(JSON.toJSONString(result3.getData()), GzhPerInfoVo.class);

		GzhPerInfoVo gzhPerInfoVo = null;
		for (GzhPerInfoVo gzhPerInfoVo1 : list) {
			if (gzhPerInfoVo1.getComId().equals(changePersonVo.getComId()) &&
					gzhPerInfoVo1.getPId().equals(changePersonVo.getPId())) {
				gzhPerInfoVo = gzhPerInfoVo1;
				break;
			}
		}

		if (gzhPerInfoVo == null) {
			return ResultUtil.error(ResultEnum.Err_2036);
		}

		Map<String, Object> mapRes = new HashMap<>();

		GzhUserInfo userInfo = changePersonVo.getUserInfo();
		userInfo.setComId(gzhPerInfoVo.getComId());
		userInfo.setPId(gzhPerInfoVo.getPId());
		userInfo.setPasswordCorrect(true);
		userInfo.setFlag(true);
		userInfo.setLoginSecret(RandomUtil.getRandomString(20));

		Gson gson = new Gson();
		String token = RSAHelper.encipher(gson.toJson(userInfo), RsaConfig.publicKey, 200);
		log.info("登录Token:" + token);

		redisUtil.set("gzhToken:" + userInfo.getComId() + ":" + userInfo.getPId(), gson.toJson(userInfo),31536000l);

		mapRes.put("token", token);

		return ResultUtil.success(mapRes);

	}


	@PostMapping(WxServiceUrl.URL_getPersonInfo)
	public Result getPersonInfo(@RequestBody Map<String, Object> map) {
		GzhAppNameVo appNameVo = JSON.parseObject(JSON.toJSONString(map), GzhAppNameVo.class);
		return humanClientService.getXfUserInfo(appNameVo.getUserInfo().getComId(), appNameVo.getUserInfo().getPId());
	}

	@PostMapping(WxServiceUrl.Url_getPersonDetail)
	public Result getPersonDetail(@RequestBody Map<String, Object> map) {
		GetPersonDetailRequest request = JSON.parseObject(JSON.toJSONString(map), GetPersonDetailRequest.class);
		UserInfoVo userInfoVo = new UserInfoVo();
		GzhUserInfo userInfo = request.getUserInfo();
		userInfoVo.setComId(Long.valueOf(userInfo.getComId()));
		userInfoVo.setPId(userInfo.getPId().intValue());
		userInfoVo.setOnlyOne(true);
		Result result = humanClientService.PersonnelGetPersonInfo(userInfoVo);
		if (200 != result.getCode()) {
			return result;
		}
		EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityPersonnelInfo.class);

		Result account = payConfigClientService.GetXFAccount(entityPersonnelInfo.getComId(), entityPersonnelInfo.getPId().intValue(), -1);
		if (account.getCode() == 200 && account.getData() != null) {
			EntityXfAccountInfo entityXfAccountInfo = JSON.parseObject(JSON.toJSONString(account.getData()), EntityXfAccountInfo.class);
			entityPersonnelInfo.setAccountEndDate(entityXfAccountInfo.getEndDate());
		}

		Result cardInfoByCardNo = payConfigClientService.GetCardInfoByPid(entityPersonnelInfo.getComId(), entityPersonnelInfo.getPId());
		if (200 == cardInfoByCardNo.getCode() && null != cardInfoByCardNo.getData()) {
			EntityCardInfo entityCardInfo = JSON.parseObject(JSON.toJSONString(cardInfoByCardNo.getData()), EntityCardInfo.class);
			entityPersonnelInfo.setCardNo(entityCardInfo.getCardNo());
			entityPersonnelInfo.setCardState(entityCardInfo.getCardState());
			entityPersonnelInfo.setEndDate(entityCardInfo.getEndDate());
		}

		return ResultUtil.success(entityPersonnelInfo);
	}

	@PostMapping(WxServiceUrl.Url_modifyPersonInfo)
	public Result modifyPersonInfo(@RequestBody  Map<String, Object> map){
		ModifyPersonInfoRequest request = JSON.parseObject(JSON.toJSONString(map), ModifyPersonInfoRequest.class);

		GzhUserInfo userInfo = request.getUserInfo();
		request.setComId(userInfo.getComId());
		request.setPId(userInfo.getPId());

		PersonVo personVo = JSON.parseObject(JSON.toJSONString(request), PersonVo.class);
		return humanClientService.UpdatePerson(personVo);
	}

	@PostMapping(WxServiceUrl.Url_modifyCardState)
	public Result modifyCardState(@RequestBody  Map<String, Object> map){
		ModifyCardStateRequest request = JSON.parseObject(JSON.toJSONString(map), ModifyCardStateRequest.class);

		GzhUserInfo userInfo = request.getUserInfo();

		Result cardInfoByCardNo = payConfigClientService.GetCardInfoByPid(userInfo.getComId(), userInfo.getPId());
		if (200 != cardInfoByCardNo.getCode() || null == cardInfoByCardNo) {
			return ResultUtil.error(ResultEnum.Err_816);
		}
		EntityCardInfo entityCardInfo = JSON.parseObject(JSON.toJSONString(cardInfoByCardNo.getData()), EntityCardInfo.class);

		UpdatecardStateVo updatecardStateVo = new UpdatecardStateVo();
		updatecardStateVo.setComId(userInfo.getComId());
		updatecardStateVo.setCardState(request.getCardState());
		updatecardStateVo.setCardNo(entityCardInfo.getCardNo());
		updatecardStateVo.setPId(userInfo.getPId());
		updatecardStateVo.setAccountNo(entityCardInfo.getAccountNo());
		updatecardStateVo.setUser(userInfo.getPId().toString());
		return payConfigClientService.UpdatecardState(updatecardStateVo);
	}


	@PostMapping(WxServiceUrl.URL_getQrCode)
	public Result getQrCode(@RequestBody Map<String, Object> map) throws IOException, WriterException {
		GzhUserInfo gzhUserInfo = (GzhUserInfo) map.get("userInfo");
//		GzhUserInfo gzhUserInfo = new GzhUserInfo();
//		gzhUserInfo.setComId(47l);
//		gzhUserInfo.setPId(2566l);
		StringBuilder stringBuilder = new StringBuilder();
		//鑫澳康付款码标识 XAK
		stringBuilder.append("58414b");
		//单位编号 5
		stringBuilder.append(HexStringUtil.IntToHexStringNum(gzhUserInfo.getComId().intValue(), 10));
		//码类型标识	Int（1）	1-付款码+门禁码，其他预留
		stringBuilder.append("01");
		//卡是否正常标识	Int（1）	bit_0位为门禁标识位，1-正常，允许开门，0-不正常，不允许开门；bit_1位为消费标识位，1-正常，允许消费，0-不正常，不允许消费；
		stringBuilder.append("01");
		//工号	Int（4）	由后台定
		String pIdHex = HexStringUtil.IntToHexStringNum(gzhUserInfo.getPId().intValue(), 8);
//        stringBuilder.append(NumConvertUtil.reverseHex(pIdHex));
		stringBuilder.append(pIdHex);
//        卡类	Int（1）	16 进制字符，01~FF，即收费类别，比如 FF,表示是 255 卡类

		String pType = "01";
		String money = "00000000";
		//返回余额
		try {
			Result result = humanClientService.getXfUserInfo(gzhUserInfo.getComId(), gzhUserInfo.getPId());
			if (result.getCode() == 200) {
				XfUserInfoVo xfUserInfoVo = JSONObject.parseObject(JSON.toJSONString(result.getData()), XfUserInfoVo.class);
				money = NumConvertUtil.IntToHexStringNum(xfUserInfoVo.getChargeBalance(), 8);
				if(xfUserInfoVo.getAccTypeId()!=null){
					pType = NumConvertUtil.IntToHexStringNum(xfUserInfoVo.getAccTypeId().intValue(), 2);
				}
			}
		} catch (Exception e) {
			log.info("获取余额 【{}】", e);
		}
		if(CommonUtil.isNull(money)){
			money = "00000000";
		}
		if(CommonUtil.isNull(pType)){
			pType = "01";
		}
		stringBuilder.append(pType);
//        借贷记模式标志	Int（1）	脱机消费时，是否验余额，1-贷记模式（不验余额） 0-借记
		stringBuilder.append("01");
//        模式（要求验余额）
//        单次消费限额	Int（2）	16 进制字符，单位：分，消费大于此值，终端拒绝消费，例
//        如：14 表示 0x14，为 20 分，最大值为 0xFFFF，即 65535 分
		stringBuilder.append("ffff");
//        余额	Int（4）	16 进制字符，单位：分，例如：14 表示 0x14，为 20 分，最
//        大为 0xFFFFFF，即 255*255*255 分


		stringBuilder.append(money);
//        发码时间戳	Int（4）	Unix 时间戳
		String timestamp = String.valueOf(new Date().getTime() / 1000);
		stringBuilder.append(NumConvertUtil.IntToHexStringNum(Integer.valueOf(timestamp), 8));         // new Date()为获取当前系统时间
//        有效时间跨度	Int（1）	16 进制字符，单位：分钟，例如：14 表示 0x14，为 20 分钟，
//        最大为 0xFFFF，即 255*255, 二维码有效期  A= 发码时间戳+ 有效时间跨度 *60
	//	stringBuilder.append("02");


		Result<List<EntityCompanyConfig>> result3 = companyClientService.getCompanyConfig(gzhUserInfo.getComId(),"qrCodeValidity");
		if(result3.getCode()==200 && result3.getData() !=null && result3.getData().size()>0 ){
			String minStr = NumConvertUtil.IntToHexStringNum(Integer.valueOf(result3.getData().get(0).getConfig()), 2);
			stringBuilder.append(minStr);
			log.info("公众号二维码有效期时间配置 J9Ln0jW4 【{}】 【{}】",gzhUserInfo.getComId(),minStr);
		}else{
			stringBuilder.append("05");
		}

//        时钟允许误差	Int（1）	判断二维码生成时间是否有效的误差允许值，单位为秒，默认 5 秒
		stringBuilder.append("0a");

//        String data2= MD5.MD5Encode(stringBuilder.substring(6),"utf8");
		String data2 = stringBuilder.substring(6);

		String secKey = "EBAB7A0EEC89A627CF21595EAC64295307CC28CF02F3B284C8707A0638F4D609";

		try {
			RespMachMessage respMachMessage = srvpaccessClientService.getDecodeKey(gzhUserInfo.getComId(),"",3);
			if(respMachMessage.getCode().equals("0000")){
				KeySecret secret = JSON.parseObject(JSON.toJSONString(respMachMessage.getData()), KeySecret.class);
				secKey=secret.getSecret().get("private_pri");
				log.info("获取单位密钥 【{}】",respMachMessage );
			}
		}catch (Exception e){
			log.info("获取密钥异常",e);
		}
		if(CommonUtil.isNull(secKey)){
			secKey = "EBAB7A0EEC89A627CF21595EAC64295307CC28CF02F3B284C8707A0638F4D609";
		}
		log.info("使用单位密钥 【{}】",secKey );

		String url = "http://120.78.153.235:20000/o2api/Api/MenJin/GetJavaQRCode?key="+secKey+"&data=" + data2;

		String tt = HttpRequest.sendGet(url);

//        签名数据	Int（64）	长度为 64字节的 SM2 私钥签名数据
		//   stringBuilder.append("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
		stringBuilder.append(tt.replace("\"", ""));

		log.info("个人二维码:【{}】【{}】【{}】【{}】【{}】",gzhUserInfo.getPId(),gzhUserInfo, data2, tt, stringBuilder);

		String code64 = QRCodeUtil.createQRCode(Base64.getEncoder().encodeToString(NumConvertUtil.hexStringToByte(stringBuilder.toString())), 600, 600);
		return ResultUtil.success(code64);
	}


	//2.1.1通过学工号、密码绑定（n=1）


	@PostMapping(WxServiceUrl.URL_bindByCodePwd)
	public Result bindByCodePsw(@RequestBody Map<String, Object> map) {
		GzhUserInfo gzhUserInfo = (GzhUserInfo) map.get("userInfo");
		String pCode = (String) map.get("code");
		String pwd = (String) map.get("pwd");

		log.info("绑定参数：【{}】",map);

		if(CommonUtil.isNull(pCode) || CommonUtil.isNull(pwd) ){
			log.info("绑定参数：【{}】【{}】",pCode,pwd);
			return ResultUtil.error(ResultEnum.Err_203);
		}


		if(CommonUtil.isNull(gzhUserInfo.getAppId()) || CommonUtil.isNull(gzhUserInfo.getOpenId()) ){
			return ResultUtil.info(500,"appid或者opneid为空");
		}

//		Result result = companyClientService.getAppInfoByName(gzhUserInfo.getAppName());
//		if (result.getCode() != 200) {
//			return result;
//		}

//		EntityWechatAppInfo entityWechatAppInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityWechatAppInfo.class);

		Map<String, Object> map3 = new HashMap<>();
		map3.put("comId", gzhUserInfo.getComId());
		map3.put("pCode", pCode);
		map3.put("page", 1);
		map3.put("size", 1);
		Result result2 = humanClientService.PersonnelGetPersonInfo(map3);
		if (result2.getCode() != 200) {
			return ResultUtil.error(result2.getCode());
		}
		String list = JSON.parseObject(JSON.toJSONString(result2.getData())).get("list").toString();
		List<UserInfoYkmVo> userInfoYkmVos = JSON.parseArray(list, UserInfoYkmVo.class);
//		Map<String, Object> map1 = new HashMap<>();
		if (userInfoYkmVos.size() > 0) {
			UserInfoYkmVo userInfoYkmVo = userInfoYkmVos.get(0);
			//密码等级低
			if (CommonUtil.isNull(userInfoYkmVo.getPPwd()) || userInfoYkmVo.getPPwd().equals("123456")
					|| userInfoYkmVo.getPPwd().equals("000000")) {
				gzhUserInfo.setPasswordCorrect(false);
			}
			if (CommonUtil.isNull(userInfoYkmVo.getPPwd()) || !userInfoYkmVo.getPPwd().equals(pwd)) {
				return ResultUtil.error(ResultEnum.Err_311);
			}
			gzhUserInfo.setComId(userInfoYkmVo.getComId());
			gzhUserInfo.setPId(userInfoYkmVo.getPId());
			String token;
			try {
				Gson gson = new Gson();

				token = RSAHelper.encipher(gson.toJson(gzhUserInfo), RsaConfig.publicKey, 200);
				log.info("登录Token:" + token);

				redisUtil.set("gzhToken:" + gzhUserInfo.getComId() + ":" + gzhUserInfo.getPId(), gson.toJson(gzhUserInfo),31536000l);
			} catch (Exception e) {
				log.info("登录生成token异常 【{}】", e);
				return ResultUtil.error(ResultEnum.Err_4003);
			}
			try {
				EntityWechatPerInfo entityWechatPerInfo = new EntityWechatPerInfo();
				entityWechatPerInfo.setComId(userInfoYkmVo.getComId());
				entityWechatPerInfo.setPId(userInfoYkmVo.getPId());
				entityWechatPerInfo.setAppid(gzhUserInfo.getAppId());
				entityWechatPerInfo.setOpenid(gzhUserInfo.getOpenId());
				humanClientService.addWxper(entityWechatPerInfo);
			} catch (Exception e) {
				log.info("gzh添加微信人员异常 【{}】", e);
			}
			//返回数据
			Map<String, Object> map4 = new HashMap<>();
			map4.put("token", token);
			map4.put("type", 0);
			map4.put("flag", true);
			map4.put("passwordCorrect", true);
			map4.put("existPerson", true);
			return ResultUtil.success(map4);

		}
		return ResultUtil.error(ResultEnum.Err_2036);

	}


	//2.1.2通过姓名、电话号码绑定（n=2）
	@PostMapping(WxServiceUrl.URL_bindByNamePhone)
	public Result bindByNamePhone(@RequestBody Map<String, Object> map) {
		GzhUserInfo gzhUserInfo = (GzhUserInfo) map.get("userInfo");
		String name = (String) map.get("name");
		String phone = (String) map.get("phone");

		log.info("绑定参数：【{}】",map);

		if(CommonUtil.isNull(name) || CommonUtil.isNull(phone) ){
			log.info("绑定参数：【{}】【{}】",name,phone);
			return ResultUtil.error(ResultEnum.Err_203);
		}

		Result result = companyClientService.getAppInfoByName(gzhUserInfo.getAppName());
		if (result.getCode() != 200) {
			return result;
		}
		EntityWechatAppInfo entityWechatAppInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityWechatAppInfo.class);

		Map<String, Object> map3 = new HashMap<>();
		map3.put("comId", entityWechatAppInfo.getComId());
		map3.put("pName", name);
		map3.put("pPhone", phone);
		map3.put("page", 1);
		map3.put("size", 1);
		Result result2 = humanClientService.PersonnelGetPersonInfo(map3);
		if (result2.getCode() != 200) {
			return ResultUtil.error(result2.getCode());
		}
		String list = JSON.parseObject(JSON.toJSONString(result2.getData())).get("list").toString();
		List<UserInfoYkmVo> userInfoYkmVos = JSON.parseArray(list, UserInfoYkmVo.class);
		Map<String, Object> map1 = new HashMap<>();
		if (userInfoYkmVos.size() > 0) {
			UserInfoYkmVo userInfoYkmVo = userInfoYkmVos.get(0);
			gzhUserInfo.setComId(userInfoYkmVo.getComId());
			gzhUserInfo.setPId(userInfoYkmVo.getPId());
			String token;
			try {
				Gson gson = new Gson();

				token = RSAHelper.encipher(gson.toJson(gzhUserInfo), RsaConfig.publicKey, 200);
				log.info("登录Token:" + token);

				redisUtil.set("gzhToken:" + gzhUserInfo.getComId() + ":" + gzhUserInfo.getPId(), gson.toJson(gzhUserInfo),31536000l);
			} catch (Exception e) {
				log.info("登录生成token异常 【{}】", e);
				return ResultUtil.error(ResultEnum.Err_4003);
			}

			try {
				EntityWechatPerInfo entityWechatPerInfo = new EntityWechatPerInfo();
				entityWechatPerInfo.setComId(userInfoYkmVo.getComId());
				entityWechatPerInfo.setPId(userInfoYkmVo.getPId());
				entityWechatPerInfo.setAppid(gzhUserInfo.getAppId());
				entityWechatPerInfo.setOpenid(gzhUserInfo.getOpenId());
				humanClientService.addWxper(entityWechatPerInfo);
			} catch (Exception e) {
				log.info("gzh添加微信人员异常 【{}】", e);
			}
			//返回数据
			Map<String, Object> map4 = new HashMap<>();
			map4.put("token", token);
			map4.put("type", 0);
			map4.put("flag", true);
			map4.put("passwordCorrect", true);
			map4.put("existPerson", true);
			return ResultUtil.success(map4);

		}
		return ResultUtil.error(ResultEnum.Err_2036);

	}


	//2.1.3通过卡号、密码绑定（n=3）
	@PostMapping(WxServiceUrl.URL_bindByCardPwd)
	public Result bindByCardPwd(@RequestBody Map<String, Object> map) {
		GzhUserInfo gzhUserInfo = (GzhUserInfo) map.get("userInfo");
		String cardNo = (String) map.get("cardNo");
		String pwd = (String) map.get("pwd");

		log.info("绑定参数：【{}】",map);

		if(CommonUtil.isNull(cardNo) || CommonUtil.isNull(pwd) ){
			log.info("绑定参数：【{}】【{}】",cardNo,pwd);
			return ResultUtil.error(ResultEnum.Err_203);
		}

		Result result = companyClientService.getAppInfoByName(gzhUserInfo.getAppName());
		if (result.getCode() != 200) {
			return result;
		}
		EntityWechatAppInfo entityWechatAppInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityWechatAppInfo.class);

		Result cardInfoByCardNo = payConfigClientService.getCardInfoByCardNo(entityWechatAppInfo.getComId(), cardNo);
		if (200 != cardInfoByCardNo.getCode() || null == cardInfoByCardNo) {
			return ResultUtil.error(ResultEnum.Err_816);
		}
		EntityCardInfo entityCardInfo = JSON.parseObject(JSON.toJSONString(cardInfoByCardNo), EntityCardInfo.class);

		Map<String, Object> map3 = new HashMap<>();
		map3.put("comId", entityWechatAppInfo.getComId());
		map3.put("pId", entityCardInfo.getPId());
		map3.put("page", 1);
		map3.put("size", 1);
		Result result2 = humanClientService.PersonnelGetPersonInfo(map3);
		if (result2.getCode() != 200) {
			return ResultUtil.error(result2.getCode());
		}
		String list = JSON.parseObject(JSON.toJSONString(result2.getData())).get("list").toString();
		List<UserInfoYkmVo> userInfoYkmVos = JSON.parseArray(list, UserInfoYkmVo.class);

		if (userInfoYkmVos.size() > 0) {
			UserInfoYkmVo userInfoYkmVo = userInfoYkmVos.get(0);
			//密码等级低
			if (CommonUtil.isNull(userInfoYkmVo.getPPwd()) || userInfoYkmVo.getPPwd().equals("123456")
					|| userInfoYkmVo.getPPwd().equals("000000")) {
				gzhUserInfo.setPasswordCorrect(false);
			}
			if (CommonUtil.isNull(userInfoYkmVo.getPPwd()) || !userInfoYkmVo.getPPwd().equals(pwd)) {
				return ResultUtil.error(ResultEnum.Err_311);
			}
			gzhUserInfo.setComId(userInfoYkmVo.getComId());
			gzhUserInfo.setPId(userInfoYkmVo.getPId());
			String token;
			try {
				Gson gson = new Gson();

				token = RSAHelper.encipher(gson.toJson(gzhUserInfo), RsaConfig.publicKey, 200);
				log.info("登录Token:" + token);

				redisUtil.set("gzhToken:" + gzhUserInfo.getComId() + ":" + gzhUserInfo.getPId(), gson.toJson(gzhUserInfo));
			} catch (Exception e) {
				log.info("登录生成token异常 【{}】", e);
				return ResultUtil.error(ResultEnum.Err_4003);
			}
			try {
				EntityWechatPerInfo entityWechatPerInfo = new EntityWechatPerInfo();
				entityWechatPerInfo.setComId(userInfoYkmVo.getComId());
				entityWechatPerInfo.setPId(userInfoYkmVo.getPId());
				entityWechatPerInfo.setAppid(gzhUserInfo.getAppId());
				entityWechatPerInfo.setOpenid(gzhUserInfo.getOpenId());
				humanClientService.addWxper(entityWechatPerInfo);
			} catch (Exception e) {
				log.info("gzh添加微信人员异常 【{}】", e);
			}
			//返回数据
			Map<String, Object> map4 = new HashMap<>();
			map4.put("token", token);
			map4.put("type", 0);
			map4.put("flag", true);
			map4.put("passwordCorrect", true);
			map4.put("existPerson", true);
			return ResultUtil.success(map4);

		}
		return ResultUtil.error(ResultEnum.Err_2036);

	}

//	@PostMapping(WxServiceUrl.URL_getPerBySmsCode)
//	public Result getPerBySmsCode(@RequestBody Map<String, String> map) {
//		String smsCode = map.get("smsCode");
//		String appName =  map.get("appName");
//
//		Result result = companyClientService.GetRegCodeInfo(smsCode);
//		if(result.getCode()!=200){
//			return result;
//		}
//		EntityEcardRegCode ecardRegCode = JSON.parseObject(JSON.toJSONString(result.getData()),EntityEcardRegCode.class);
//
//		Result result1  = companyClientService.getCompanyInfoById(ecardRegCode.getComId());
//
//		EntityCompanyInfo entityCompanyInfo =JSON.parseObject(JSON.toJSONString(result1.getData()),EntityCompanyInfo.class);
//
//
//		UserInfoVo userInfoVo =new UserInfoVo();
//		userInfoVo.setComId(ecardRegCode.getComId());
//		userInfoVo.setPId(ecardRegCode.getPId().intValue());
//		userInfoVo.setOnlyOne(true);
//
//		Result result2 = humanClientService.PersonnelGetPersonInfo(userInfoVo);
//		if(result2.getCode()!=200){
//			return result2;
//		}
//
//		EntityPersonnelInfo entityPersonnelInfo =JSON.parseObject(JSON.toJSONString(result2.getData()),EntityPersonnelInfo.class);
//
//		Map<String,Object> resMap =new HashMap<>();
//		resMap.put("comId",ecardRegCode.getComId());
//		resMap.put("comName",entityCompanyInfo.getComName());
//		resMap.put("pId",ecardRegCode.getPId());
//		resMap.put("phone",entityPersonnelInfo.getPPhone());
//		resMap.put("url",entityPersonnelInfo.getPPhotoUrl2());
//
//		return ResultUtil.success(resMap);
//
//
//	}

}
